package com.franklin.ideaplugin.easytesting.spring.config;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author Ye Junhui
 * @since 2023/6/24 18:13
 */
@Data
@Configuration
public class MyServerProperties implements EnvironmentAware {

    private Environment environment;

    private String servletPath;

    private String servletContextPath;

    private String port = "8080";

    public String getPort(){
        return this.port;
    }

    /**
     * 前缀
     * @return
     */
    public String getPrefix(){
        String prefix = "";

        if (StrUtil.isNotBlank(this.servletPath)){
            prefix = this.servletPath;
        }
        if (StrUtil.isNotBlank(this.servletContextPath)){
            prefix = this.servletContextPath;
        }
        if (StrUtil.isNotBlank(prefix) && !prefix.startsWith("/")){
            prefix = "/" + prefix;
        }
        return prefix;
    }

    /**
     * 服务路径
     * @return
     */
    public String getServerPath(){
        return  "http://127.0.0.1:" + this.getPort() + this.getPrefix();
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
        this.servletPath = this.environment.getProperty("server.servlet.path","");
        this.servletContextPath = this.environment.getProperty("server.servlet.context-path","");
        this.port = this.environment.getProperty("server.port","8080");
    }
}
